package vn.gq.tym.model;

import java.util.List;

import vn.gq.tym.storytemplate.R;
import vn.gq.udv.db.DbAdapter;
import vn.gq.udv.db.items.ChapterItem;
import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ChapterItemAdapter extends BaseAdapter {

	private List<ChapterItem> mChapterList;
	private LayoutInflater mInflater;
	private Context mContext;
	
	private Handler mHandler = new Handler();
	
	public ChapterItemAdapter(Context context) {
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mContext = context;
	}
	
	@Override
	public int getCount() {
		return mChapterList.size();
	}
	
	public void load(final int catId, final Runnable run) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				mChapterList = new DbAdapter(mContext).getChapterItems(catId);
				mHandler.post(run);
			}
		}).start();
	}

	@Override
	public Object getItem(int position) {
		return mChapterList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}
	
	public List<ChapterItem> getData() {
		return mChapterList;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		ViewHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.item_list, parent, false);
			holder = new ViewHolder();
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		ChapterItem item = (ChapterItem) getItem(position);
		holder.tvTitle = (TextView) convertView.findViewById(R.id.text_view);
		holder.tvTitle.setText(item.getTitle());
		
		return convertView;
	}
	
	private class ViewHolder {
		
		public TextView tvTitle;
		
	}

}
